package com.ynrcc.util;

import java.util.ArrayList;
import java.util.List;

import com.eova.common.utils.EncryptUtil;
import com.eova.config.EovaInit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class MigratePerson {

	// 如果有子机构返回true，否则返回false
	public static void getSubOrgs(String fdId, List<String> orgs) {
		String sql = "select * from ekp.sys_org_element where fd_org_type='2' and fd_parentid ='" + fdId
				+ "' and fd_id not in (select fd_id from com_brch where fd_id is not null) order by fd_order";
		List<Record> records = Db.find(sql);
		if (records.size() < 1) {
			return;
		}
		for (Record record : records) {
			orgs.add(record.getStr("FD_ID"));
			//System.out.println(record.getStr("FD_NAME"));
			getSubOrgs(record.getStr("FD_ID"), orgs);
		}
	}

	public static void main(String[] args) {
		EovaInit.initConfig();

		if (ConnDB.connDB())
			System.out.println("数据库连接成功！");
		else {
			System.out.println("数据库连接失败，返回！");
		}

		List<String> orgs = new ArrayList<String>();
		List<String> persons = new ArrayList<String>();

		// 遍历所有机构
		String sql = "select * from com_brch where fd_id is not null order by brchcd";
		List<Record> records = Db.find(sql);
		for (Record record : records) {
			System.out.println("[" + record.getStr("BRCHNA") + "]");
			orgs.clear();
			orgs.add(record.getStr("FD_ID"));
			getSubOrgs(record.getStr("FD_ID"), orgs);

			// 遍历该机构下所有人员
			for (String org : orgs) {
				System.out.println("----[" + org + "]");
				persons.clear();
				sql = "select * from ekp.sys_org_element where fd_org_type='8' and fd_parentid ='" + org
						+ "' order by fd_order";
				List<Record> recordsOfPerson = Db.find(sql);
				for (Record person : recordsOfPerson) {
					sql = "select * from ekp.sys_org_person where fd_id = '" + person.getStr("FD_ID") + "'";
					Record recordPerson = Db.findFirst(sql);
					System.out.print(recordPerson.getStr("FD_LOGIN_NAME") + "|");
					
					//插入数据库
					// 取主键
					sql = "select SEQ_EOVA_USER.nextval SEQ from dual";
					int seq = Db.findFirst(sql).getInt("SEQ");

					Record user = new Record().set("ID", seq).set("LOGIN_ID", recordPerson.getStr("FD_LOGIN_NAME"));
					user.set("LOGIN_PWD", recordPerson.getStr("FD_PASSWORD"));
					user.set("NAME", recordPerson.getStr("FD_LOGIN_NAME")).set("RID", 33);
					user.set("BRCHCD", record.getStr("BRCHCD"));
					user.set("PHONE", recordPerson.getStr("FD_WORK_PHONE"));
					user.set("MOBILE", recordPerson.getStr("FD_MOBILE_NO"));
					Db.save("eova_user", user);
				}
			}
		}
	}
}
